import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { Cell, CellGroup, Input, Checkbox, Button } from "react-vant";
import { addOrcPerson, switchState } from "../../store/orcPerson";
import { useNavigate } from "react-router-dom";
import axios from "axios";
const Index = () => {
  // 从redux中获取orcPerson的总人数
  const list = useSelector((state) => state.orcPerson.totalOrcPersons);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const handleUpload = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.click();

    input.onchange = async () => {
      const file = input.files[0];
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = async () => {
        const base64 = fileReader.result;
        const startIndex = base64.indexOf(",") + 1;
        const base64Data = base64.substring(startIndex);
        // 发送给百度

        // 1. 登录百度
        const AK = "imsmA7O8WtX193NSfCdDolhp";
        const SK = "6Y9XEjQFGX81nv5ClpniD6ZbEDG2nOTS";
        function getAccessToken() {
          let options = {
            method: "POST",
            url:
              "/baidu/oauth/2.0/token?grant_type=client_credentials&client_id=" +
              AK +
              "&client_secret=" +
              SK,
          };
          return new Promise((resolve, reject) => {
            axios(options)
              .then((res) => {
                resolve(res.data.access_token);
              })
              .catch((error) => {
                reject(error);
              });
          });
        }
        // 2. 调用orc 识别图片身份证
        async function getResult() {
          var options = {
            method: "POST",
            url:
              "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" +
              (await getAccessToken()),
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              Accept: "application/json",
            },
            // image 可以通过 getFileContentAsBase64("C:\fakepath\下载.png") 方法获取,
            data: {
              id_card_side: "front",
              image: base64Data,
              detect_ps: "false",
              detect_risk: "false",
              detect_quality: "false",
              detect_photo: "false",
              detect_card: "false",
              detect_direction: "false",
            },
          };
          return axios(options)
        }
        const result = await getResult()
        const data = {
          id: Math.random().toString(),
          name: result.data.words_result['姓名'].words,
          identityCard: result.data.words_result['公民身份号码'].words,
          state: false
        }
        dispatch(addOrcPerson(data))
      };
    };
  };
  return (
    <div>
      <Button block round type="info" onClick={() => handleUpload()}>
        没有要选择的乘车人，添加
      </Button>
      <CellGroup>
        {list.map((v) => {
          return (
            <Cell
              key={v.id}
              title={
                <div style={{ display: "flex" }}>
                  <Checkbox
                    checked={v.state}
                    style={{ width: 30 }}
                    // 点击切换选中状态
                    onClick={() => dispatch(switchState(v))}
                  ></Checkbox>
                  {v.name}-{v.identityCard}
                </div>
              }
            ></Cell>
          );
        })}
      </CellGroup>
      <Button block round type="primary" onClick={() => navigate(-1)}>
        确定
      </Button>

      <input type="file" />
    </div>
  );
};

export default Index;
